#!/usr/bin/python
# -*- coding: UTF-8 -*-

# TODO:
#     1.Dupilcated Filenames Error ** Fixed with exception handling.
#
#
#
"""Test code

Suggested usage: import batchrename
"""
__decription__ = "Batch Rename Kit"
__version__    = "0.1"
__date__       = " Feb.17th.2007"
__author__     = "hu <huys03@gmail.com> "
__license__    = "Licensed under the GPLv2, see the file LICENSE in this tarball."
__copyright__  = "Copyright (C) 2007 by hu <huys03@gmail.com>."

from ConfigParser import RawConfigParser
from time import sleep
import string
import os
import errno
import sys


class BatchRename:
###
    def __init__ (self, cfgFile='text.ini', path=os.getcwd()):
        self.cfgFile = cfgFile
        self.path = path
        self.count = 0

###
    def loadcfg(self):
        cfg = RawConfigParser()
        cfg.read(self.cfgFile)

        self.cap = cfg.get( 'KeyString', 'captials' ).split()
        self.spe = cfg.get( 'KeyString', 'specials' ).split()

        self.sym = cfg.get( 'DeleteString', 'symbols' ).split()
        self.sea = cfg.get( 'DeleteString', 'seasons' ).split()
        self.aut = cfg.get( 'DeleteString', 'authors' ).split()

        self.ext = cfg.get( 'FileType', 'extensions' ).split()

###
    def getFilenames(self):
        self.files = []
        for f in os.listdir( self.path ) :
            (filename, ext) = os.path.splitext(f)
            if ext.lower() in self.ext:
                self.files.append(f)
                self.count += 1

###
    def format(self, filename):
        filename = string.lower(filename)
        filename = string.replace(filename, "&", "and")
        for s in self.sym:
            filename = string.replace(filename, s, " ")

        for s in self.sea:
            filename = string.replace(filename, s, "")

        filename = string.capwords(filename)
        filename = string.replace(filename, " ", ".")

        for s in self.aut:
            filename = string.replace(filename, s, "")

        for s in self.cap:
            if string.capwords(s) in filename.split("."):
                filename = string.replace(filename, string.capwords(s), s)

        for s in self.spe:
            if string.capwords(s) in filename.split("."):
                filename = string.replace(filename, string.capwords(s), s)

        filename = string.replace(filename, " ", "")

        return filename

    def rename(self):
        for oldfile in self.files:
            (filename, ext) = os.path.splitext(oldfile)
            newfile = self.format(filename) + ext

            try:
                os.rename(oldfile, newfile)
            except OSError, e:
                if e.errno <> errno.EEXIST:
                    raise
                else:
                    print "Duplicated filename:"
                    print "   " + oldfile + " ==> " + newfile
                    sys.exit(1)

            print newfile


###
    def run(self):
        print "==============================="
        print __decription__
        print 'version:', __version__
        print __license__
        print __copyright__
        print "==============================="
        self.loadcfg()
        self.getFilenames()
        if self.count == 0:
            print "No valid file was found... "
        else:
            self.rename()

###
if __name__=="__main__":
    rn = BatchRename()
    rn.run()
    sleep(5)

